#include "Logger.h"


//#define LOGTOFILE 


#ifdef LOGTOFILE
#define LOGFILENAME "openro.log"
#endif

#ifdef WIN32
#include <windows.h>
#endif



Logger::Logger()
{
#ifdef LOGTOFILE
	m_fpLog.open( LOGFILENAME, std::ios::in );
	if( m_fpLog.is_open() )
	{
		m_fpLog.close();
		m_fpLog.open( LOGFILENAME, std::ios::out | std::ios::app );
	}
	else
	{
		m_fpLog.open( LOGFILENAME, std::ios::out );
		m_fpLog << FileHeader(DateStamp());
	}

	//replace cout with fstream.
	std::streambuf *oldbuf = std::cout.rdbuf(m_fpLog.rdbuf()); 
	
	// print out a file header to the file
	std::cout << FileHeader(DateStamp());
#endif
}

Logger* Logger::Instance()
{
	static Logger instance;

	return &instance;
}

bool __cdecl Logger::Log(MSG_TYPE type, const char* pstrFmtString, ...)
{
	char szBuf[BUF_SIZE] = { 0 };
	va_list args;
	va_start(args, pstrFmtString);
	int nSize = _vsnprintf( szBuf, sizeof(szBuf) - 1, pstrFmtString, args); // C4996
	va_end(args); 
	
	if (nSize >= BUF_SIZE - 1)
	{
		assert(0);
		return false;
	}

	return Log(type, string(szBuf));
}

string Logger::FileHeader(const std::string& p_title)
{
	return "==================================================\n" +
		p_title + "\n" +
		"==================================================\n\n";
}

string Logger::DateStamp()
{
	char str[11];

	// get the time, and convert it to struct tm format
	time_t a = time(0);
	struct tm* b = localtime( &a );

	// print the time to the string
	strftime( str, 11, "%Y.%m.%d", b );

	return str;
}

string Logger::TimeStamp()
{
	char str[9];

	// get the time, and convert it to struct tm format
	time_t a = time(0);
	struct tm* b = localtime( &a );

	// print the time to the string
	strftime( str, 9, "%H:%M:%S", b );

	return str;
}

bool Logger::Log(MSG_TYPE type,const string& strInfo)
{
	string info;
	 switch(type)
	 {
	 case MSG_STATUS:
		 std::cout << TimeStamp() << "[Status]:"<< strInfo<<std::endl;
		 break;
	 case MSG_ERROR:
		 std::cout << TimeStamp() <<"[ERROR]:"<< strInfo<<std::endl;
		 break;
	 case MSG_WARNING:
		 std::cout << TimeStamp() <<"[WARNNING]:"<< strInfo<<std::endl;
		 break;
	 case MSG_DEBUG:
#ifdef WIN32
		 info = TimeStamp() + "[DEBUG]" + strInfo;
		 OutputDebugString(info.c_str());
#endif
	 default:
		 break;
	 }

	 return true;
}